from flask import Flask, request, jsonify
from PIL import Image
import io
import easyocr
import base64
import numpy as np
import threading
ocr_engine = easyocr.Reader(['ch_sim', 'en'])
ocr_lock = threading.Lock()  # 用于同步访问 OCR 引擎
from flask_cors import CORS
app = Flask(__name__)

CORS(app, origins="http://localhost:8080")  # Allow requests from localhost:8080 (your front-end)

def userNameOcr(path_or_base64):
    global ocr_engine
    with ocr_lock:
        if path_or_base64.startswith('data:image'):
            # 去除 base64 字符串中的头部信息（例如 'data:image/jpeg;base64,'）
            path_or_base64 = path_or_base64.split(',')[1]
        # 打开图片
        # image = Image.open(path)
        image_data = base64.b64decode(path_or_base64)  # 解码 base64 字符串
        image = Image.open(io.BytesIO(image_data))  # 将字节数据转换为图片
        # 截取用户姓名和用户信息区域
        userName_image = image.crop((0, 2070, 1080, 2200))

        # 将 PIL 图像转换为 numpy 数组
        userName_image_np = np.array(userName_image)
        ocr_results = ocr_engine.readtext(userName_image_np, detail=0)
        print(ocr_results)
        user = ''.join(ocr_results[0:len(ocr_results) - 1])

        if len(user)<= 0:
            return True
        else:
            return False


@app.route('/ocr', methods=['POST'])
def ocr():

    if 'base64' in request.json:
        path_or_base64 = request.json['base64']
        text = imgOcr(path_or_base64)
        return jsonify({"result": text})
    else:
        return jsonify({"error": "No image or base64 data found in request."}), 400


def imgOcr(path_or_base64):
    global ocr_engine
    with ocr_lock:

        if path_or_base64.startswith('data:image'):
            image_data = base64.b64decode(path_or_base64.split(',')[1])  # Strip data URL prefix
        else:
            image_data = base64.b64decode(path_or_base64)

        # Convert byte data to a PIL image
        with io.BytesIO(image_data) as buffer:
            with Image.open(buffer) as image:

                temp_image = image.crop((0, 712, 1080, 1500))  # Adjust coordinates as needed

                userName_image_np = np.array(temp_image)

                ocr_results = ocr_engine.readtext(userName_image_np, detail=0)
                print(ocr_results)  # Debug output of OCR result

                return ocr_results  # Return OCR text

@app.route('/', methods=['GET'])
def index():
    return "Hello Flask!"

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=39800, debug=True)
